import { AbsFormUtil } from '@abstract/form';
import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { IBaseAddr } from '@model/base';
import { AuthService } from '@service/auth.service';
import { BaseService } from '@service/base.service';
import { TreeService } from '@service/tree.service';
import { deepClone } from '@utils/lang';
import { NzMessageService } from 'ng-zorro-antd/message';
import { saveAs as importedSaveAs } from 'file-saver';
const ID = 123456789;
@Component({
	selector: 'app-base-addr',
	templateUrl: './base-addr.component.html',
	styleUrls: ['./base-addr.component.less']
})
export class BaseAddrComponent extends AbsFormUtil implements OnInit {
	nzLoading = false;
	data = [];
	editData: IBaseAddr = null;
	type = '1';
	list = [];
	constructor(
		private baseService: BaseService,
		private nzMessageService: NzMessageService,
		private fb: FormBuilder,
		private treeService: TreeService,
		private authService: AuthService,
		private route: ActivatedRoute,

	) {
		super();
		this.page.limit = 1000;
	}

	get isQrCode() {
		return this.type === '1';
	}
	ngOnInit() {
		this.buildForm();
		this.route.params.subscribe(data => {
			this.type = data.id;
			this.onSearch();
			this.authList = this.authService.getAuth();
		});
	}

	buildForm() {
		this.validateForm = this.fb.group({
			areaFullName: ['']
		});
	}

	async onSearch() {
		this.nzLoading = true;
		const formValue = this.validateForm.value;
		// formValue.parentId = 0;
		// formValue.areaLevel = 0;
		const result = await this.baseService.getAddrList({parentId:0, areaLevel: 0});
		this.nzLoading = false;
		this.list = result.data;
		const treeData = this.treeService.convertListToTree(result.data || [], 0);
		this.data = this.treeService.convertTreeToList(treeData);
		if (formValue.areaFullName) {
			this.data.forEach(itm => {
				itm.isSel = itm.areaFullName.includes(formValue.areaFullName) || itm.areaName.includes(formValue.areaFullName);
				itm.expand = true;
			});
		}
		this.data = [...this.data];
		this.page.total = this.data.length;
	}

	collapse(item, $event: boolean) {
		if (!$event) {
			if (item.children) {
				item.children.forEach(d => {
					const target = this.data.find(a => a.id === d.id)!;
					target.expand = false;
					this.collapse(target, false);
				});
			} else {
				return;
			}
		}
	}

	// private async getNextNodeInfo(data: ISystemOrganize, flag?: boolean) {
	// 	data.expand = true;
	// 	data.isSpinning = true;
	// 	setTimeout(() => {
	// 		const res = [{
	// 			deptName: '镇北社区居委会001' + Math.random(),
	// 			id: Math.random().toString(),
	// 			children: [],
	// 		}, {
	// 			deptName: '镇北社区居委会002' + Math.random(),
	// 			id: Math.random().toString(),
	// 			children: [],
	// 		},]
	// 		const nodeInfoList = res.map(itm => {
	// 			itm['level'] = data.level + 1;
	// 			itm['parent'] = data;
	// 			return itm;
	// 		});
	// 		data.children = nodeInfoList as ISystemOrganize[];
	// 		const index = this.data.findIndex(it => it.id === data.id);
	// 		this.data.splice(index + 1, 0, ...nodeInfoList);
	// 		this.data = [...this.data];
	// 		console.log(this.data);
	// 		data.isSpinning = false;
	// 		if (flag) {
	// 			this.createNode(data);
	// 		}
	// 	}, 1000);
	// }
	add(item?: IBaseAddr) {
		if (this.editData) {
			this.nzMessageService.info('一次只能编辑一条数据!');
			return;
		}
		if (item) {
			item.expand = true;
			item.children = item.children ? item.children : []
		}
		console.log(item);
		const node = new IBaseAddr();
		// const uuid = getUuid();
		// node.id = uuid;
		node.id = ID;
		node.level = item ? item.level + 1 : 0;
		node.children = null;
		node.parent = item ? item : null;
		const idx = item ? this.data.findIndex(itm => itm.id === item.id) : -1;
		this.data.splice(idx + 1, 0, node)
		this.data = [...this.data];
		this.editData = node;
	}
	


	edit(item: IBaseAddr) {
		if (this.editData) {
			this.nzMessageService.info('一次只能编辑一条数据!');
			return;
		}
		this.editData = deepClone(item);
	}
	async del(item: IBaseAddr) {
		await this.baseService.deleteAddr(item.id);
		this.nzMessageService.success('删除成功');
		// const idx = this.data.findIndex(it => it.id === item.id);
		// this.data.splice(idx, 1);
		this.delChild(item);
		if (item.parent) {
			const id = item.parent.id;
			if (!this.data.some(it => it.parent && it.parent.id === id)) {
				const parent = this.data.find(it => it.id === id);
				parent.children = null;
			}
		}
		this.data = [...this.data];
	}
	delChild(item) {
		const index = this.data.findIndex(it => it.id === item.id);
		this.data.splice(index, 1);
		if (item.children?.length) {
			item.children.forEach(itm => {
				this.delChild(itm);
			});
		}
	}
	async save(item: IBaseAddr) {
		if (!this.editData.areaFullName) {
			this.nzMessageService.error('区域全称不能为空')
			return;
		}
		if (!this.editData.areaName) {
			this.nzMessageService.error('区域名称不能为空')
			return;
		}
		const message = this.nzMessageService.loading('保存中...')
		const editData = this.editData;
		const body = {
			parentId: editData.parent ? editData.parent.id : 0,
			areaName: editData.areaName ,
			areaFullName: editData.areaFullName,
			mergerName: '',
			id: editData.id === ID ? '' : editData.id,
			areaLevel: editData.areaLevel ?  editData.areaLevel : 0
		};
		const result = await this.baseService.saveAddr(body);
		this.nzMessageService.remove(message.messageId);
		if (result.status === 214) {
			this.nzMessageService.info('该部门名称已存在，请重新填写！');
			return;
		}
		item.id === ID ? this.onSearch() : '';
		if (item.id !== ID) {
			item.areaFullName = editData.areaFullName;
			item.areaName = editData.areaName;
		}
		this.editData = null;
		this.nzMessageService.success('保存成功');
	}
	cancel(item: IBaseAddr) {
		if (item.id === ID) {
			const idx = this.data.findIndex(it => it.id === item.id);
			this.data.splice(idx, 1);
			if (item.parent) {
				const id = item.parent.id;
				if (!this.data.some(it => it.parent && it.parent.id === id)) {
					const parent = this.data.find(it => it.id === id);
					parent.children = null;
				}
			}
			this.data = [...this.data];
		}
		this.editData = null;
	}


	downloadQrCode(item) {
		const result = this.getAddrName(item, [item]);
		console.log(result);
		const fileName = result.map(it => it.areaFullName).join(',');
		this.baseService.downloadQrCode(item, fileName);
	}
	getAddrName(area, result: any[]) {
		const areaItem = this.list.find(itm => itm.id * 1 === area.parentId);
		if (areaItem) {
			result.unshift(areaItem);
			if (areaItem.parentId) {
				return this.getAddrName(areaItem, result);
			}
			return result;
		}
		return result;
	}
}
